# coding:utf-8
from flask import render_template, redirect, url_for, request, flash

from . import blue_recover
from ..Models.models import user, Role, run_mode, db_recover_scheme, db_recover_scheme_detail, scheme_attr, \
	basic_sql_command
from .. import db
from db_recover.flask_celery import add
from db_recover import db_init

@blue_recover.before_app_first_request
def init_data():
	dd=db_init.db_init_run(db=db,
            run_mode=run_mode,
            basic_sql_command=basic_sql_command,
            user=user,
            Role=Role,
            db_recover_scheme_detail=db_recover_scheme_detail,
            db_recover_scheme=db_recover_scheme,
            scheme_attr=scheme_attr)

	dd.init_data()




@blue_recover.route('/hello/<name>')
def hello(name=None):
	print name
	r = Role.query.filter_by(name='Admin').first()
	u = user(username='john1', password='123', email='aa@aa111.com', role=r)
	db.session.add(u)
	db.session.commit()

	return render_template('hello.html')


@blue_recover.route('/recovr/recoverdb', methods=["GET", "POST"])
def recoverdb():
	# celery
	# d=add.delay(1,2)
	# print d.result
	# print d.state

	###数据库
	
	desc=request.args['scheme']
	scheme = db_recover_scheme.query.filter_by(desc=desc).first()  # 从一 获取所有 多
	dict_scheme_sql = {}

	print scheme.scheme_detail.order_by(db_recover_scheme_detail.step).all()  ##排序

	for d in scheme.scheme_detail.all():
		_d = {}
		_d.setdefault('sql', d.basic_sql_command.cmd_sql)  # 从多获取到一,backref
		_d.setdefault('run_mode', d.run_mode.mode)
		_d.setdefault('verify_str', d.verify_str)
		_d.setdefault('ip', d.scheme_attr.run_ip)
		if _d['run_mode'].find('sql') != -1:
			_d.setdefault('ip', d.scheme_attr.db_sid)
		dict_scheme_sql.setdefault(d.step, _d)

	for x,y in dict_scheme_sql.items():
		print x,y

	return render_template('index.html')


@blue_recover.route('/', methods=["GET", "POST"])
def index():
	return redirect(url_for('blue_recover.recoverdb'))


@blue_recover.route('/login', methods=['GET', 'POST'])
def login():
	error = None
	if request.method == 'POST':
		if request.form['username'] != 'admin' or \
						request.form['password'] != '111':
			error = 'Invalid credentials'
		else:
			# app.logger.debug('A value for debugging')
			flash('You were successfully logged in')  # 只能 当前页可以，返回到index则不行
			return redirect(url_for('index'))
	return render_template('login.html', error=error)
